package com.principles.structure.hedonic;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description 享元模式————运用共享技术有效的支持大量细类度的对象  （池技术，线程池，连接池。。。。。。）
 *              可以被共享的元素，资源可以被复用，一部分是共享的，另一部分是各不相同的
 *              优点：通过池技术，可以极大的减少内存中对象数量，使相同或相似对象在内存中只保留一份，大大节约系统资源和性能
 *              缺点：程序逻辑复杂。外部状态都需要传入影响运行时间
 * @Date 2025/1/28 13:16
 **/
public class FlyWeightPattern {
    public static void main(String[] args) {
        BikeFlyWeight bike = BikeFlyWeightFactory.getInstance().getBike();
        bike.ride("张三");
//        bike.back();
        BikeFlyWeight bike1 = BikeFlyWeightFactory.getInstance().getBike();
        bike1.ride("张三1");
        bike1.back();

        BikeFlyWeight bike2 = BikeFlyWeightFactory.getInstance().getBike();
        bike2.ride("张三2");
    }
}

abstract class BikeFlyWeight{
    // 内部状态
    protected Integer state = 0;
    // 外部状态
    abstract void ride(String userName);
    abstract void back();
    public Integer getState(){
        return state;
    }
}

class MoBikeFlyWeight extends BikeFlyWeight{
    private String bikeId;

    public MoBikeFlyWeight(String bikeId) {
        this.bikeId = bikeId;
    }

    @Override
    void ride(String userName) {
        state = 1;
        System.out.println(userName+"骑"+bikeId+"，自行车！");
    }

    @Override
    void back() {
        state = 0;
    }
}

// 需要工厂模式创建，创建池
class BikeFlyWeightFactory{
    private static BikeFlyWeightFactory instance = new BikeFlyWeightFactory();
    private Set<BikeFlyWeight> pool =new HashSet();

    public static BikeFlyWeightFactory getInstance(){
        return instance;
    }

    public BikeFlyWeightFactory(){
        for(int i =0;i<2;i++){
            pool.add(new MoBikeFlyWeight(i+"号"));
        }
    }

    public BikeFlyWeight getBike(){
        for(BikeFlyWeight bike : pool){
            if(bike.getState() == 0){
                return bike;
            }
        }
        return null;
    }

}


